/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.anniversary.service.impl;

import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.anniversary.domain.News;
import me.zhengjie.modules.anniversary.repository.NewsRepository;
import me.zhengjie.modules.anniversary.service.NewsService;
import me.zhengjie.modules.anniversary.service.dto.NewsDto;
import me.zhengjie.modules.anniversary.service.dto.NewsQueryCriteria;
import me.zhengjie.modules.anniversary.service.mapstruct.NewsMapper;
import me.zhengjie.utils.FileUtil;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import me.zhengjie.utils.ValidationUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author Jiayin Wei
* @date 2020-07-28
**/
@Service
@RequiredArgsConstructor
public class NewsServiceImpl implements NewsService {

    private final NewsRepository newsRepository;
    private final NewsMapper newsMapper;

    @Override
    public Object queryAll(NewsQueryCriteria criteria, Pageable pageable){
        Page<News> page = newsRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(newsMapper::toDto));
    }

    @Override
    public List<NewsDto> queryAll(NewsQueryCriteria criteria){
        return newsMapper.toDto(newsRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public NewsDto findById(Long id) {
        News news = newsRepository.findById(id).orElseGet(News::new);
        ValidationUtil.isNull(news.getId(),"News","id",id);
        return newsMapper.toDto(news);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public NewsDto create(News resources) {
        return newsMapper.toDto(newsRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(News resources) {
        News news = newsRepository.findById(resources.getId()).orElseGet(News::new);
        ValidationUtil.isNull( news.getId(),"News","id",resources.getId());
        Long oldReviewerId = news.getReviewerId();
        news.copy(resources);
        if (oldReviewerId != news.getReviewerId())
        {
            news.setReviewTime(new Timestamp(System.currentTimeMillis()));
        }
        newsRepository.save(news);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            newsRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<NewsDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (NewsDto news : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("标题", news.getName());
            map.put("发布者", news.getPublisher() == null ? "" : news.getPublisher().getUsername());
            map.put("内容", news.getContent());
            map.put("审核状态（0：待审核、1：审核通过、2：审核未通过）", news.getVerifyStatus());
            map.put("审核者", news.getReviewer() == null ? "" :news.getReviewer().getUsername());
            map.put("审核时间",news.getReviewTime());
            map.put("创建者", news.getCreateBy());
            map.put("创建时间", news.getCreateTime());
            map.put("修改者", news.getUpdatedBy());
            map.put("修改时间", news.getUpdateTime());
            map.put("排序", news.getSort());
            map.put("备注", news.getRemark());
            map.put("是否启用", news.getIsEnable());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    /**查找首页模块最新3条资讯信息*/
    @Override
    public List<Map<String,Object>> findByNewest(Pageable pageable){
        return newsRepository.findByNewest(pageable);
    }

    /*查找首页模块资讯信息(分页)*/
    @Override
    public List<Map<String,Object>> findByAllNews(Pageable pageable) {
        return newsRepository.findByAllNews(pageable);
    }

    @Override
    public List<Map<String,Object>> findByAllAlumniNews(Long assId,Pageable pageable) {
        return newsRepository.findByAllAlumniNews(assId,pageable);
    }

    @Override
    public List<Map<String,Object>>  queryAssociationNewslimit(Long id, Pageable pageable) {
        return newsRepository.queryAssociationNewslimit(id, pageable);
    }

    @Override
    public Map<String,Object> queryAssociationById(Long id) {
        return newsRepository.queryAssociationById(id);
    }
}
